﻿using System.Threading;
using Cysharp.Threading.Tasks;
using FairyGUI;

namespace GameFramework.UI.FairyGUI
{
    public static class FairyGUIUtility
    {
        /// <summary>
        /// 异步创建GObject
        /// </summary>
        public static async UniTask<GObject> CreateObjectAsync(string packageName, string componentName, CancellationToken cancellationToken)
        {
            var finished = false;
            GObject gObject = null;
            
            UIPackage.CreateObjectAsync(packageName, componentName, o =>
            {
                finished = true;
                gObject = o;
            });

            await UniTask.WaitUntil(() => finished, cancellationToken: CancellationToken.None);

            if (gObject == null)
                return gObject;
            
            if (!cancellationToken.IsCancellationRequested)
                return gObject;
            
            gObject.Dispose();
            return null;
        }
    }
}